// @include "../../../scripts/spket.js"

dbo.users = function(){
	var users = panda.db.get("users");
	return {
		list: function() {
			if (!users.count()) { init(); }
			return users.list().$sort({ name: 1 });
		},
		add: function(user) {
			users.insert(user);
			return this.list();
		},
		update: function(user) {
			var q = { name: user.name };
			users.update(q, user, true, false);
			return this.list();
		},
		remove: function(name) {
			users.remove({ name: name });
			return this.list();
		},
		exists: function(name) {
			return users.count({ name: name }) > 0;
		}
	};
	
	function list() {
		if (!users.count()) { init(); }
		return users.list().$sort({ name: 1 });
	}

	function init() {
		panda.db.eval(function(){
			var users = db.users;
			users.drop();
			users.ensureIndex({ name: 1 }, { unique: true });

			users.insert({ name: "user1", desc: "desc1" });
			users.insert({ name: "user2", desc: "desc2" });
			users.insert({ name: "user3", desc: "desc3" });
		});
	}
}();
